package cn.shadow.game.chess.CHnchess.board;


import cn.shadow.game.chess.CHnchess.chessman.Chess;
import cn.shadow.proto.client.CHnChessClientProtoContent;

import java.util.List;

/**
 * 实体类,表示棋盘上每一个点
 */
public class ChessPosition implements Position {

    /**
     * 固定位置
     */
    private final int ROW;
    private final int COL;
    /**
     * 当前放置在该位置的棋子可能为空
     */
    private Chess chess;

    /**
     * 所属的棋盘的表
     */
    private final Board board;


    public ChessPosition(int row, int col, Board board) {
        this.ROW = row;
        this.COL = col;
        this.board = board;
    }

    /**
     * 返回一个点的复制值
     *
     * @return
     */
    public Position copy(Chess chess) {
        Position point = new ChessPosition(this.ROW, this.COL, null);
        point.setChess(chess);
        return point;
    }


    public Chess getChess() {
        return chess;
    }

    public void setChess(Chess chess) {
        this.chess = chess;
    }

    @Override
    public boolean isOverRanged() {
        return this.COL < 0 || this.COL >= Board.COL
                || this.ROW < 0 || this.ROW >= Board.ROW;
    }

    public Board getBoard() {
        return board;
    }

    /**
     * @return 获得键值
     */
    public int getKey() {
        return 100 * ROW + COL;
    }

    @Override
    public int getRow() {
        return ROW;
    }

    @Override
    public int getCol() {
        return COL;
    }

    /**
     * @return 是否在主将的局域
     */
    @Override
    public boolean isInCenter() {
        List<Integer> centerArea = CenterArea.getCenterArea(isDown());
        return centerArea.contains(getKey());
    }

    /**
     * 行大于4为黑色方,
     *
     * @return
     */
    @Override
    public boolean isDown() {
        return ROW > 4;
    }

    public String show() {
        StringBuilder sb = new StringBuilder();
        Chess chess = getChess();
        if (chess == null) {
            sb.append("\t");
        } else {
            sb.append(chess.getType().getName()).append("[").append(chess.getCamp().getName()).append("]").append("  ");
        }
        return sb.toString();

    }

    @Override
    public String toString() {
        return ROW + "," + COL;
    }


    /**
     * 返回一个点的复制值
     *
     * @return
     */
    public Position copy(Chess chess, Board board) {
        Position point = new ChessPosition(this.ROW, this.COL, board);
        if (chess == null) {
            return point;
        }
        point.setChess(chess);
        chess.setPosition(point);
        return point;
    }

    @Override
    public CHnChessClientProtoContent.ChessNode chessNodeMsg() {
        CHnChessClientProtoContent.ChessNode.Builder builder = CHnChessClientProtoContent.ChessNode.newBuilder();
        if (chess != null) {
            builder.setChess(chess.chessMsg());
        }
        builder.setPosX(getCol());
        builder.setPosY(getRow());
        return builder.build();
    }

}
